package org.thraex.excel.example;

import org.thraex.excel.vo.DetailVO;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.stream.Collectors;

/**
 * @Author 鬼王
 * @Date 2019/08/12 12:45
 */
public class MyRunnable implements Runnable {

    private final CountDownLatch countDown;
    private final CountDownLatch await;

    private DetailVO vo;

    public MyRunnable(CountDownLatch countDown, CountDownLatch await, DetailVO vo) {
        this.countDown = countDown;
        this.await = await;
        this.vo = vo;
    }

    @Override
    public void run() {
        try {
            countDown.await();
            System.out.println("Handle anticipated work....." + this.vo.getDeptName());
            await.countDown();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        CountDownLatch countDown = new CountDownLatch(1);
        CountDownLatch await = new CountDownLatch(5);

        // 依次创建并启动处于等待状态的5个MyRunnable线程
        for (int i = 0; i < 10; ++i) {
            DetailVO vo = new DetailVO();
            vo.setDeptName("name" + i);
            new Thread(new MyRunnable(countDown, await, vo)).start();
        }

        System.out.println("用于触发处于等待状态的线程开始工作......");
        System.out.println("用于触发处于等待状态的线程工作完成，等待状态线程开始工作......");
        countDown.countDown();
        await.await();
        System.out.println("Bingo!");

//        sortResult();
    }

    private static void sortResult() {
        System.out.println(Arrays.asList(
                5, 18, 9, 3, 6, 22, 2,
                4, 33, 1, 34, 37, 25, 30,
                29, 49, 15, 23, 26, 21, 17,
                45, 31, 14, 13, 35, 10, 32,
                24, 43, 0, 27, 19, 12, 11,
                47, 41, 7, 38, 42, 36, 20,
                28, 48, 8, 16, 44, 40, 46, 39)
                .stream().sorted().collect(Collectors.toList())
        );
    }
}
